import type { GithubTypeResult } from './types'
import { PageRoute } from '../../../abstract/page_route'
import { GithubPageType } from './types'

export class GithubPage extends PageRoute {
  readonly name: string = 'GithubPage'
  private static instance: GithubPage
  get pageType(): GithubPageType | 'default' {
    return this.getCurrentPageMeta().type
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): GithubPage {
    if (!GithubPage.instance) {
      GithubPage.instance = new GithubPage()
    }
    return GithubPage.instance
  }

  /**
   * 获取当前页面类型
   */
  public getCurrentPageMeta(): GithubTypeResult {
    const url = this.getCurrentUrl()
    const path = new URL(url).pathname

    // 404 页面检测
    const notFoundResult = this.detectNotFoundPage()
    if (notFoundResult)
      return notFoundResult

    // 首页
    if (/^\/?$/.test(path)) {
      return { type: GithubPageType.Index }
    }

    if ($('#repo-content-turbo-frame').length) {
      // 项目页面
      if (/^\/[^/]+\/[^/]+$/.test(path)) {
        return { type: GithubPageType.Project }
      }
      // 项目页面点击文件后会进入代码视图页面
      else if ($('react-app[app-name="react-code-view"]').length) {
        return { type: GithubPageType.CodeView }
      }
    }

    // 基础页面检测
    const pageResult = this.detectPages(path)
    if (pageResult)
      return pageResult

    // 未定义页面
    return { type: GithubPageType.Undefined }
  }

  /**
   * 检测 404 页面
   */
  private detectNotFoundPage(): GithubTypeResult | null {
    const pageNotFoundRules = [
      /404.*Not Found/i, // 不区分大小写
    ]

    if (pageNotFoundRules.some(regex => regex.test(document.title))) {
      return { type: GithubPageType.NotFound }
    }

    return null
  }

  /**
   * 检测其他功能页面
   */
  private detectPages(basePath: string): GithubTypeResult | null {
    const pageDetectors: Array<[RegExp, (...args: any[]) => GithubTypeResult]> = [
      // 提交记录
      [/^\/([^/]+)\/([^/]+)\/commits\/([^/]+)\/?$/, () => {
        return { type: GithubPageType.Commits }
      }],
      // 标签
      [/^\/([^/]+)\/([^/]+)\/tags\/?$/, () => {
        return { type: GithubPageType.Tags }
      }],
    ]

    for (const [regex, handler] of pageDetectors) {
      const match = basePath.match(regex)
      if (match) {
        return handler(match)
      }
    }

    return null
  }
}
